package com.fortune.controller;

import cn.hutool.core.util.RandomUtil;
import com.fortune.conf.*;
import com.fortune.dto.NewsDTO;
import com.fortune.entity.NewsEntity;
import com.fortune.service.NewsService;
import com.fortune.vo.PageResult;
import com.fortune.vo.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import us.codecraft.webmagic.Spider;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.time.LocalDate;
import java.util.List;

import static com.fortune.conf.GifCompressorFFmpeg.extremeCompress;
import static com.fortune.conf.ImageCompressor.compressImage;
import static com.fortune.conf.PngCompressor.compressPng;
import static com.fortune.conf.Utils.getAllFiles;

@RestController
@RequestMapping("/news")
public class NewsController {

    private static final String IP_LOCALHOST ="127.0.0.1";
    @Autowired
    private NewsService newsService;

//    @GetMapping(value = "getNewsList")
//    public String getNewsList(){
//        return "获取数据成功";
//    }

    @PostMapping(value = "getNewsList")
    @OperationLog(logType="Query",describe="获取消息列表")
    public RestResult<PageResult<List<NewsEntity>>> getNewsList(@RequestBody NewsDTO newsDTO) {
        PageResult<List<NewsEntity>> data = newsService.getNewsList(newsDTO);
        return new RestResult<>(RestResult.SUCCESS_CODE, "获取列表数据成功", data);
    }
    @GetMapping(value = "getNewsDetailsById")
    @OperationLog(logType="QueryDetails",describe="获取消息详情")
    public RestResult<NewsEntity> getNewsDetailsById(@RequestParam  Integer newsId) {
        NewsEntity newsEntity = newsService.getNewsDetailsById(newsId);
        return new RestResult<>(RestResult.SUCCESS_CODE, "获取详情成功", newsEntity);
    }

    @GetMapping(value = "getNewsByNet")
    @OperationLog(logType="getNewsByNet",describe="基于网络获取文章信息")
    public RestResult<String> getDetailsNyNet(@RequestParam String urlStr,@RequestParam String typeCode) throws InterruptedException {
        //urlStr url要获取的页面 url  ，typeCode 1 '历史', '2故事', 3'美图', '4视频', '5搞笑'
        if(urlStr.contains("www.sohu.com")){
            Spider.create(new SOHUPageNewsSpider()).addUrl(urlStr).addPipeline(new SavePipelineDate(typeCode)).thread(3).run();
        }
        if(urlStr.contains("www.toutiao.com")){
            String[] types = {"1","2"};
            TOUTIAOPageNewsSpider tOUTIAOPageNewsSpider = new TOUTIAOPageNewsSpider();
            tOUTIAOPageNewsSpider.getNewsList(urlStr,types[RandomUtil.randomInt(1,3)-1]);
        }

        return new RestResult<>(RestResult.SUCCESS_CODE, "获取成功", "获取成功");
    }
}

